import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authAPI from '../api/auth';

// 异步登录操作
export const login = createAsyncThunk(
  'auth/login',
  async (credentials, { rejectWithValue }) => {
    try {
      const response = await authAPI.login(credentials);
      // 将token和用户信息保存到localStorage
      localStorage.setItem('token', response.token);
      localStorage.setItem('userInfo', JSON.stringify(response.userInfo));
      return response;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '登录失败');
    }
  }
);

// 异步登出操作
export const logout = createAsyncThunk(
  'auth/logout',
  async () => {
    try {
      await authAPI.logout();
    } finally {
      // 清除localStorage中的token和用户信息
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    }
  }
);

// 初始化状态
const initialState = {
  isAuthenticated: false,
  userInfo: null,
  token: null,
  loading: false,
  error: null,
};

// 从localStorage中恢复状态
const savedToken = localStorage.getItem('token');
const savedUserInfo = localStorage.getItem('userInfo');

if (savedToken && savedUserInfo) {
  initialState.isAuthenticated = true;
  initialState.userInfo = JSON.parse(savedUserInfo);
  initialState.token = savedToken;
}

// 创建authSlice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 清除错误信息
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      // 登录中
      .addCase(login.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      // 登录成功
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.userInfo = action.payload.userInfo;
        state.token = action.payload.token;
        state.error = null;
      })
      // 登录失败
      .addCase(login.rejected, (state, action) => {
        state.loading = false;
        state.isAuthenticated = false;
        state.userInfo = null;
        state.token = null;
        state.error = action.payload;
      })
      // 登出成功
      .addCase(logout.fulfilled, (state) => {
        state.isAuthenticated = false;
        state.userInfo = null;
        state.token = null;
        state.error = null;
      });
  },
});

// 导出action creator
export const { clearError } = authSlice.actions;

// 导出reducer
export default authSlice.reducer;